package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.IAppointSchoolService;
import com.xmy.cultivate.service.IEnrollRoyaltySetService;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 招生提成设置 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-09-11
 */
@RestController
@RequestMapping("/api/enrollRoyaltySet")
public class EnrollRoyaltySetController {
    @Autowired
    IEnrollRoyaltySetService iEnrollRoyaltySetService;

    @Autowired
    IAppointSchoolService iAppointSchoolService;

    @Autowired
    IOrganizationService iOrganizationService;


    @GetMapping()
    public Result getEnrollStagePeriod(@RequestParam Map<String, String> reMap) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));
        IPage<EnrollRoyaltySet> iPage = new Page<>(pageNum, pageSize);

        String level = reMap.get("level");
        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String schoolId = reMap.get("schoolId");
        String status = reMap.get("status");

        iEnrollRoyaltySetService.getAll(iPage, startDate, endDate, schoolId, level, status);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }


    @PostMapping()
    public Result addEnrollRoyaltySet(@RequestBody EnrollRoyaltySet enrollRoyaltySet) {
        // 判断校区、时间段是否重复添加
        if (enrollRoyaltySet.getOpeningSchoolType() == 1) {
            // 判断全部校区的时间段是否冲突
            Integer countByDate = iEnrollRoyaltySetService.countByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), enrollRoyaltySet.getLevel());
            if (countByDate > 0) {
                String reminder = "提示：【全部校区 " + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已存在，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }
        } else if (enrollRoyaltySet.getOpeningSchoolType() == 2 && Objects.nonNull(enrollRoyaltySet.getSchoolList())) {
            // 判断是否已经添加过全部校区
            Integer countByDate = iEnrollRoyaltySetService.countByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), enrollRoyaltySet.getLevel());
            if (countByDate > 0) {
                String reminder = "提示：【" + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已添加过全部校区，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }

            // 判断指定校区的时间段是否冲突
            StringBuffer schoolNameSb = new StringBuffer();
            for (Long schoolId : enrollRoyaltySet.getSchoolList()) {
                countByDate = iEnrollRoyaltySetService.countAppointSchoolByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), schoolId);
                if (countByDate > 0) {
                    String schoolName = iOrganizationService.getSchoolName(schoolId);
                    if (schoolNameSb.length() > 0 && !"null".equals(schoolNameSb.toString()) && !"".equals(schoolNameSb.toString())) {
                        schoolNameSb.append("、");
                    }
                    schoolNameSb.append(schoolName);
                }
            }
            if (schoolNameSb.length() > 0 && !"null".equals(schoolNameSb.toString()) && !"".equals(schoolNameSb.toString())) {
                String reminder = "提示：【" + schoolNameSb + " " + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已存在，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }
        }

        iEnrollRoyaltySetService.save(enrollRoyaltySet);

        if (enrollRoyaltySet.getOpeningSchoolType() == 2 && Objects.nonNull(enrollRoyaltySet.getSchoolList())) {
            for (Long schoolId : enrollRoyaltySet.getSchoolList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(enrollRoyaltySet.getId());
                appointSchool.setSchoolId(schoolId);
                appointSchool.setType(6);
                iAppointSchoolService.save(appointSchool);
            }
        }

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }


    @PutMapping()
    public Result putEnrollRoyaltySet(@RequestBody EnrollRoyaltySet enrollRoyaltySet) {
        // 判断校区、时间段是否重复添加
        if (enrollRoyaltySet.getOpeningSchoolType() == 1) {
            // 判断全部校区的时间段是否冲突
            Integer countByDate = iEnrollRoyaltySetService.countByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), enrollRoyaltySet.getLevel());
            if (countByDate > 1) {
                String reminder = "提示：【全部校区 " + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已存在，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }
        } else if (enrollRoyaltySet.getOpeningSchoolType() == 2 && Objects.nonNull(enrollRoyaltySet.getSchoolList())) {
            // 判断是否已经添加过全部校区
            Integer countByDate = iEnrollRoyaltySetService.countByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), enrollRoyaltySet.getLevel());
            if (countByDate > 1) {
                String reminder = "提示：【" + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已添加过全部校区，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }

            // 判断指定校区的时间段是否冲突
            StringBuffer schoolNameSb = new StringBuffer();
            for (Long schoolId : enrollRoyaltySet.getSchoolList()) {
                countByDate = iEnrollRoyaltySetService.countAppointSchoolByDate(enrollRoyaltySet.getStartDate(), enrollRoyaltySet.getEndDate(), schoolId);
                if (countByDate > 1) {
                    String schoolName = iOrganizationService.getSchoolName(schoolId);
                    if (schoolNameSb.length() > 0 && !"null".equals(schoolNameSb.toString()) && !"".equals(schoolNameSb.toString())) {
                        schoolNameSb.append("、");
                    }
                    schoolNameSb.append(schoolName);
                }
            }
            if (schoolNameSb.length() > 0 && !"null".equals(schoolNameSb.toString()) && !"".equals(schoolNameSb.toString())) {
                String reminder = "提示：【" + schoolNameSb + " " + enrollRoyaltySet.getStartDate() + " 至 " + enrollRoyaltySet.getEndDate() + "】该时间段已存在，请勿重复添加";
                return new Result(Code.ERROR, null, reminder);
            }
        }

        iEnrollRoyaltySetService.updateById(enrollRoyaltySet);

        if (enrollRoyaltySet.getOpeningSchoolType() == 2 && Objects.nonNull(enrollRoyaltySet.getSchoolList())) {
            iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id", enrollRoyaltySet.getId()));
            for (Long schoolId : enrollRoyaltySet.getSchoolList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(enrollRoyaltySet.getId());
                appointSchool.setSchoolId(schoolId);
                appointSchool.setType(6);
                iAppointSchoolService.save(appointSchool);
            }
        }

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }


    @DeleteMapping("/{id}")
    public Result deleteEnrollRoyaltySet(@PathVariable(value = "id") Long id) {
        EnrollRoyaltySet enrollRoyaltySet = iEnrollRoyaltySetService.getById(id);
        if (enrollRoyaltySet.getOpeningSchoolType() == 2) {
            iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id", id));
        }
        iEnrollRoyaltySetService.removeById(id);

        return new Result(Code.OK, "", Code.OK_MSG);
    }

}
